package com.shengchang.hu.supervision.UI;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.posapi.PosApi;
import android.posapi.PosApi.OnCommEventListener;
import android.posapi.PrintQueue;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.zyapi.CommonApi;

import com.magicrf.uhfreader.UhfReaderDevice;
import com.magicrf.uhfreader.Util;
import com.magicrf.uhfreaderlib.reader.UhfReader;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.BitmapTools;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;



public class CheckOutActivity extends BaseActivity implements View.OnClickListener {



    InBoundBar checkedbar;

    /* 读取UFH*/
    private boolean runFlag = true;
    private boolean startFlag = false;
    private boolean connectFlag = false;
    private boolean powerOn = false;
    private String serialPortPath = "/dev/ttyMT2";
    private UhfReader reader;
    private UhfReaderDevice readerDevice;
    CommonApi mCommonApi;
    private int mComFd = -1;
    private String Uhfdata;
    /*打印功能*/
    private String time = "2019-05-13";
    private String type = "损伤类";
    private String Weigets = "1.6";
    private String code = "123456789";
    private String DName = "1";
    private String codename;
    Bitmap btMap;
    private String timeNow;
    boolean isCanPrint = true;
    private PosApi mPosSDK = null;
    private PrintQueue mPrintQueue = null;

    /*扫描*/
    private String mCoder;
    MediaPlayer player;
    private byte mGpioPower = 0x1E;// PB14
    private byte mGpioTrig = 0x29;// PC9

    private int mCurSerialNo = 3; // usart3
    private int mBaudrate = 4; // 9600
    StringBuilder sb=new StringBuilder();
    private ScanBroadcastReceiver scanBroadcastReceiver;
    private long mPressedBackTime;
    Handler mhandle = new Handler();
    private static final String Terminal_checkRubbishInRepeat = Contants.Terminal_checkRubbishInRepeat;
    private static final String Terminal_replenishmentInRubbishIhInBox = Contants.Terminal_replenishmentInRubbishIhInBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_check_out);
        checkedbar=findViewById(R.id.checkedbar);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        }

    private void initScan() {
        //注册获取扫描信息的广播接收器
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(PosApi.ACTION_POS_COMM_STATUS);
        registerReceiver(receiver, mFilter);

        // 物理扫描键按下时候会有动作为ismart.intent.scandown的广播发出，可监听该广播实现触发扫描动作
        scanBroadcastReceiver = new ScanBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ismart.intent.scandown");
        this.registerReceiver(scanBroadcastReceiver, intentFilter);
        // 扫描提示音
        player = MediaPlayer.create(getApplicationContext(),
                R.raw.beep);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
//                            initPos();

                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }

            }
        }).start();
        initScan();
        getNowTime();


    }
    private void getNowTime() {
        long currentTime = System.currentTimeMillis();
        timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);

    }

    /**
     * 扫描信息获取
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equalsIgnoreCase(PosApi.ACTION_POS_COMM_STATUS)) {
                // 串口标志判断
                int cmdFlag = intent.getIntExtra(PosApi.KEY_CMD_FLAG, -1);
                // 获取串口返回的字节数组
                byte[] buffer = intent
                        .getByteArrayExtra(PosApi.KEY_CMD_DATA_BUFFER);
                switch (cmdFlag) {
                    // 如果为扫描数据返回串口
                    case PosApi.POS_EXPAND_SERIAL3:
                        if (buffer == null)
                            return;
                        try {
                            // 将字节数组转成字符串
                            final String str = new String(buffer, "UTF-8");

                                   player.start();
                            if (str != null) {

                                check(str);

                            } else {
                                showShortToast("扫码失败，请重新扫描");
                            }


                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                // 扫描完本次后清空，以便下次扫描
                buffer = null;
            }
        }
    };


    public void check(String str) {
        Pattern pattern = Pattern.compile(str);
        Matcher matcher = pattern.matcher(sb.toString());
        if (!matcher.find()) {
            sb.append(str + ",");
            ChecedQRRequest(str);

        } else {
            showShortToast("不可重复扫描");
        }

    }
    private void ChecedQRRequest(final String barcode) {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCode", barcode)
                .build();
        Request request = new Request.Builder()
                .url(Terminal_checkRubbishInRepeat)
                .post(formBody)
                .build();
        Log.d("ckRubbishInRepeat", Terminal_checkRubbishInRepeat + "?id=" + App.getApp().getToken() + "&rubbishCode=" + barcode);
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String checedstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ChecedResPonse(checedstr);
                    }
                });

            }
        });
    }

    private void ChecedResPonse(String checedstr) {
        try {
            JSONObject checedjson = new JSONObject(checedstr);
            String checedjsonString = checedjson.getString("message");
            if (checedjsonString.equals("20005")) {
                dismissProgressDialog();
                showShortToast("请求成功");
//                sb.append(mCoder + ",");
//                Log.d("sbdsdee", sb.toString());
//                showProgressDialog();
//                Handler mhandle = new Handler();
//                mhandle.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        showProgressDialog();
//                        ScanCodeRequest(sb.toString());
//                    }
//                }, 20);

            } else if (checedjsonString.equals("20006")) {
                dismissProgressDialog();
                showShortToast("不可重复之前操作");
            } else if (checedjsonString.equals("20009")) {
                dismissProgressDialog();
                showShortToast("类型不符合");
            } else if (checedjsonString.equals("20008")) {
                dismissProgressDialog();
                showShortToast("无满足条件对象");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    private void ScanCodeRequest(String str) {
        OkHttpClient moKhttpclient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCodes", str)
                .add("recordDate",timeNow)
                .build();
        Request request = new Request.Builder()
                .url(Terminal_replenishmentInRubbishIhInBox)
                .post(formBody)
                .build();
        Log.d("CODE_API", Terminal_replenishmentInRubbishIhInBox + "?id=" + App.getApp().getToken() + "&rubbishCodes=" + str+"&recordDate="+timeNow);
        Call mcall = moKhttpclient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String Codestr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CodeResponse(Codestr);
                    }
                });

            }
        });

    }

    private void CodeResponse(String codestr) {
        try {
            JSONObject codejson = new JSONObject(codestr);
            String msg = codejson.getString("message");
            if (msg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络请求异常");
            } else if (msg.equals("20005")) {
                dismissProgressDialog();
                showShortToast("入库成功");
                sb.setLength(0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
//                                Pos();
                            }
                        }, 20);                //此处会发生异常//
                    }
                }).start();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONObject datajson = new JSONObject(codestr);
            JSONObject rubbishIn = datajson.getJSONObject("rubbishIn");
            time = rubbishIn.getString("inTime");
            DName = rubbishIn.getString("count");
            code = rubbishIn.getString("inCode");
            Weigets = rubbishIn.getString("weight");
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.printcode:

                if (sb.length() == 0) {
                    showShortToast("请扫码上传");
                } else {
                    showProgressDialog();
                    Handler mhandle = new Handler();
                    mhandle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showProgressDialog();
                            ScanCodeRequest(sb.toString());
                        }
                    }, 20);
                }

                break;
            case R.id.buloubtn:
                startActivity(new Intent(CheckOutActivity.this, DamagedActivity.class));
                break;
            case R.id.chuku:
                startActivity(new Intent(CheckOutActivity.this,CheckedBulkActivity.class));
                finish();
                break;
        }
    }


//    private void initPos() {
//        // 获取PosApi实例
//        mPosSDK = PosApi.getInstance(this);
//        // 根据型号进行初始化mPosApi类
//        if (Build.MODEL.contains("LTE")
//                || Build.DISPLAY.contains("3508")
//                || Build.DISPLAY.contains("403")
//                || Build.DISPLAY.contains("35S09")) {
//            mPosSDK.initPosDev("ima35s09");
//        } else if (Build.MODEL.contains("5501")) {
//            mPosSDK.initPosDev("ima35s12");
//        } else {
//            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
//        }
//
//        //监听初始化回调结果
//        mPosSDK.setOnComEventListener(mCommEventListener);
//        // 打印队列初始化
//        mPrintQueue = new PrintQueue(this, mPosSDK);
//        // 打印队列初始化
//        mPrintQueue.init();
//        //打印队列设置监听
//        mPrintQueue.setOnPrintListener(new PrintQueue.OnPrintListener() {
//            //打印完成
//            @Override
//            public void onFinish() {
//                // TODO Auto-generated method stub
//                //打印完成
//                Toast.makeText(getApplicationContext(),
//                        getString(R.string.print_complete), Toast.LENGTH_SHORT)
//                        .show();
//                //当前可打印
//                isCanPrint = true;
//                //完成之后关掉打印功能
////
//            }
//
//            //打印失败
//            @Override
//            public void onFailed(int state) {
//                // TODO Auto-generated method stub
//                isCanPrint = true;
//                switch (state) {
//                    case PosApi.ERR_POS_PRINT_NO_PAPER:
//                        // 打印缺纸
//                        showTipDialog(getString(R.string.print_no_paper));
//                        break;
//                    case PosApi.ERR_POS_PRINT_FAILED:
//                        // 打印失败
//                        showTipDialog(getString(R.string.print_failed));
//                        break;
//                    case PosApi.ERR_POS_PRINT_VOLTAGE_LOW:
//                        // 电压过低
//                        showTipDialog(getString(R.string.print_voltate_low));
//                        break;
//                    case PosApi.ERR_POS_PRINT_VOLTAGE_HIGH:
//                        // 电压过高
//                        showTipDialog(getString(R.string.print_voltate_high));
//                        break;
//                }
//            }
//
//            @Override
//            public void onGetState(int arg0) {
//                // TODO Auto-generated method stub
//
//            }
//
//            //打印设置
//            @Override
//            public void onPrinterSetting(int state) {
//                // TODO Auto-generated method stub
//                isCanPrint = true;
//                switch (state) {
//                    case 0:
//                        Toast.makeText(CheckOutActivity.this, "持续有纸", Toast.LENGTH_SHORT).show();
//                        break;
//                    case 1:
//                        //缺纸
//                        Toast.makeText(CheckOutActivity.this, getString(R.string.no_paper), Toast.LENGTH_SHORT).show();
//                        break;
//                    case 2:
//                        //检测到黑标
//                        Toast.makeText(CheckOutActivity.this, getString(R.string.label), Toast.LENGTH_SHORT).show();
//                        break;
//                }
//            }
//        });
//    }

    /**
     * 物理SCAN按键监听
     */
    boolean isScan = false;


    class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

                                //监听到SCAN按键按下广播，执行扫描
                                ScanDomn();
                                }}

    /**
     * 执行扫描，扫描后的结果会通过action为PosApi.ACTION_POS_COMM_STATUS的广播发回
     */
    public void ScanDomn() {
        if (!isScan) {
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 300);
        } else {
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 300);
        }
    }

    Handler handler = new Handler();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 强制关闭扫描头
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            isScan = false;
        }
    };

    /**
     * 初始化
     */
    OnCommEventListener mCommEventListener = new OnCommEventListener() {
        @Override
        public void onCommState(int cmdFlag, int state, byte[] resp, int respLen) {
            // TODO Auto-generated method stub
            switch (cmdFlag) {
                case PosApi.POS_INIT:
                    if (state == PosApi.COMM_STATUS_SUCCESS) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("设备初始化成功");
                            }
                        });

                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("设备初始化失败");
                            }
                        });
                    }
                    break;
            }
        }
    };

//    //打印
//    private void Pos() {
//        try {
//            StringBuilder sb = new StringBuilder();
////            sb.append("          医废信息                ");
////            sb.append("\n");
//            sb.append("        启动人民医院      ");
//            sb.append("\n");
//            sb.append("-----------------------------");
//            sb.append("\n");
//            sb.append("重量: " + Weigets + "kg");
//            sb.append("  ");
//            sb.append("袋数: " + DName);
//            sb.append("\n");
//            sb.append("时间: " + time);
//            sb.append("\n");
//            byte[] bt = sb.toString().getBytes("GBK");
//            btMap = encode2dAsBitmap(code, 300, 300, 2);
//            byte[] printData = BitmapTools.bitmap2PrinterBytes(btMap);
//
//            mPosSDK.printText(50, bt, bt.length);
//            // 将打印数组添加到打印队列
//            mPrintQueue.addBmp(40, 40, btMap.getWidth(), btMap.getHeight(),
//                    printData);
//            mPrintQueue.addText(50, "\n\n".getBytes("GBK"));
//
//
//        } catch (
//                UnsupportedEncodingException e)
//
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        mPrintQueue.printStart();
//
//    }
//
//    public static Bitmap encode2dAsBitmap(String contents, int desiredWidth,
//                                          int desiredHeight, int barType) {
//        BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
//        if (barType == 1) {
//            barcodeFormat = BarcodeFormat.CODE_128;
//        } else if (barType == 2) {
//            barcodeFormat = BarcodeFormat.QR_CODE;
//        }
//
//        Bitmap barcodeBitmap = null;
//        try {
//            barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
//                    desiredWidth, desiredHeight);
//        } catch (WriterException e) {
//            e.printStackTrace();
//        }
//
//        return barcodeBitmap;
//    }
//
//    public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
//                                        int desiredWidth, int desiredHeight) throws WriterException {
//        final int WHITE = 0xFFFFFFFF;
//        final int BLACK = 0xFF000000;
//
//        HashMap<EncodeHintType, String> hints = null;
//        String encoding = guessAppropriateEncoding(contents);
//        if (encoding != null) {
//            hints = new HashMap<EncodeHintType, String>(2);
//            hints.put(EncodeHintType.CHARACTER_SET, encoding);
//        }
//        MultiFormatWriter writer = new MultiFormatWriter();
//        BitMatrix result = writer.encode(contents, format, desiredWidth,
//                desiredHeight, hints);
//        result = deleteWhite(result);// 删除白边
//        int width = result.getWidth();
//        int height = result.getHeight();
//        int[] pixels = new int[width * height];
//        // All are 0, or black, by default
//        for (int y = 0; y < height; y++) {
//            int offset = y * width;
//            for (int x = 0; x < width; x++) {
//                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
//            }
//        }
//
//        Bitmap bitmap = Bitmap.createBitmap(width, height,
//                Bitmap.Config.ARGB_8888);
//        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
//        return bitmap;
//    }
//
//    private static BitMatrix deleteWhite(BitMatrix matrix) {
//        int[] rec = matrix.getEnclosingRectangle();
//        int resWidth = rec[2] + 1;
//        int resHeight = rec[3] + 1;
//
//        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
//        resMatrix.clear();
//        for (int i = 0; i < resWidth; i++) {
//            for (int j = 0; j < resHeight; j++) {
//                if (matrix.get(i + rec[0], j + rec[1]))
//                    resMatrix.set(i, j);
//            }
//        }
//        return resMatrix;
//    }
//
//    public static String guessAppropriateEncoding(CharSequence contents) {
//        // Very crude at the moment
//        for (int i = 0; i < contents.length(); i++) {
//            if (contents.charAt(i) > 0xFF) {
//                return "UTF-8";
//            }
//        }
//        return null;
//    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销获取扫描数据的广播
        unregisterReceiver(receiver);

        // 注销物理SCAN按键的接收广播
        unregisterReceiver(scanBroadcastReceiver);

        if (mPrintQueue != null) {
            // 打印队列关闭
            mPrintQueue.close();
        }

        // 关闭下层串口以及打印机
        mPosSDK.closeDev();

        }

    @Override
    protected void onStop() {
        super.onStop();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        }

    @Override
    public void onBackPressed() {
        long l = System.currentTimeMillis();
        if (l - this.mPressedBackTime > 3000L) {
            showLongToast("再次轻触返回键退出程序");
            this.mPressedBackTime = l;
            return;
        }
        finish();
    }


}
